#!/bin/bash

# Health check script for monitoring
set -e

HOST=${1:-localhost}
PORT=${2:-3000}
TIMEOUT=${3:-30}

echo "🏥 Performing health check on $HOST:$PORT"

# Simple health check
if curl -f -s --max-time $TIMEOUT "http://$HOST:$PORT/api/health/simple" > /dev/null; then
    echo "✅ Simple health check passed"
else
    echo "❌ Simple health check failed"
    exit 1
fi

# Detailed health check
HEALTH_RESPONSE=$(curl -s --max-time $TIMEOUT "http://$HOST:$PORT/api/health" || echo "")

if [ -z "$HEALTH_RESPONSE" ]; then
    echo "❌ Detailed health check failed - no response"
    exit 1
fi

# Parse health response
STATUS=$(echo "$HEALTH_RESPONSE" | grep -o '"status":"[^"]*"' | cut -d'"' -f4 || echo "unknown")
UPTIME=$(echo "$HEALTH_RESPONSE" | grep -o '"uptime":[0-9]*' | cut -d':' -f2 || echo "0")
MEMORY_USED=$(echo "$HEALTH_RESPONSE" | grep -o '"used":[0-9]*' | cut -d':' -f2 || echo "0")
PLUGINS_ENABLED=$(echo "$HEALTH_RESPONSE" | grep -o '"enabled":[0-9]*' | cut -d':' -f2 || echo "0")
PLUGINS_RUNNING=$(echo "$HEALTH_RESPONSE" | grep -o '"running":[0-9]*' | cut -d':' -f2 || echo "0")

echo "📊 Health Status: $STATUS"
echo "⏱️  Uptime: ${UPTIME}s"
echo "💾 Memory Used: ${MEMORY_USED}MB"
echo "🔌 Plugins Enabled: $PLUGINS_ENABLED"
echo "▶️  Plugins Running: $PLUGINS_RUNNING"

if [ "$STATUS" != "healthy" ]; then
    echo "❌ Service is not healthy"
    exit 1
fi

echo "✅ All health checks passed"
